package com.tuanzi.loan.business.repository.family.impl;

import com.base.common.log.LogService;
import com.google.common.collect.Lists;
import com.tuanzi.loan.business.entity.family.LoanWholeSaleComment;
import com.tuanzi.loan.business.repository.family.LoanLargeAmountPlusRecordRepository;
import com.tuanzi.loan.core.repository.JOOQBaseRepositoryPlus;
import com.tuanzi.loan.vo.request.family.LoanLargeAmountPlusRecordSearchRequest;
import com.tuanzi.loan.vo.response.family.LoanLargeAmountPlusRecordSearchResponse;
import com.tuanzi.server.loan_base.util.DateUtils;
import com.tuanzi.server.loan_base.util.PhoneNumNideUtil;
import org.apache.commons.lang3.StringUtils;
import org.jooq.Condition;
import org.jooq.SelectQuery;
import org.jooq.Table;
import org.jooq.impl.DSL;
import org.jooq.impl.TableImpl;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Repository;

import java.sql.Date;
import java.text.ParseException;
import java.util.List;
import java.util.Objects;

import static com.tuanzi.loan.generated.jooq.loan.Tables.LOAN_SPECIFY_PUSH;
import static com.tuanzi.loan.generated.jooq.loan.Tables.LOAN_WHOLESALE_COMMENT;
import static com.tuanzi.loan.generated.jooq.loan.tables.LoanLargeAmountPlus.LOAN_LARGE_AMOUNT_PLUS;

@Repository
public class LoanLargeAmountPlusRecordRepositoryImpl  extends JOOQBaseRepositoryPlus implements LoanLargeAmountPlusRecordRepository {

    private List<LoanWholeSaleComment> loanList;

    @Override
    protected TableImpl getTable() {
        return LOAN_LARGE_AMOUNT_PLUS;
    }


    @Override
    public Page<LoanLargeAmountPlusRecordSearchResponse> list(LoanLargeAmountPlusRecordSearchRequest searchRequest, Pageable pageable) {
        Condition specifyCondition = DSL.trueCondition();
        if (Objects.nonNull(searchRequest.getStartDate())){
            specifyCondition = specifyCondition.and(LOAN_SPECIFY_PUSH.CREATEDATE.ge(new Date(searchRequest.getStartDate().getTime())));
        }
        if (Objects.nonNull(searchRequest.getEndDate())){
            specifyCondition = specifyCondition.and(LOAN_SPECIFY_PUSH.CREATEDATE.le(new Date(searchRequest.getEndDate().getTime())));
        }
        if (StringUtils.isNotBlank(searchRequest.getPetname())){
            specifyCondition=specifyCondition.and(LOAN_SPECIFY_PUSH.NAME.eq(searchRequest.getPetname()));
        }
        if (Objects.nonNull(searchRequest.getC_from())&&searchRequest.getC_from().size()!=0){
            specifyCondition=specifyCondition.and(LOAN_SPECIFY_PUSH.CHANNEL_ND.in(searchRequest.getC_from()));
        }
        if (Objects.nonNull(searchRequest.getStatus())){
            specifyCondition=specifyCondition.and(LOAN_SPECIFY_PUSH.STATUS.eq(searchRequest.getStatus()));
        }
        if (Objects.nonNull(searchRequest.getType())){
            specifyCondition = specifyCondition.and(LOAN_SPECIFY_PUSH.TYPE.eq(searchRequest.getType()));
        }
        Condition loanLargeAmountCondition = DSL.trueCondition();
        if (Objects.nonNull(searchRequest.getStartDate())){
            loanLargeAmountCondition = loanLargeAmountCondition.and(LOAN_LARGE_AMOUNT_PLUS.CREATEDATE.ge(new Date(searchRequest.getStartDate().getTime())));
        }
        if (Objects.nonNull(searchRequest.getEndDate())){
            loanLargeAmountCondition = loanLargeAmountCondition.and(LOAN_LARGE_AMOUNT_PLUS.CREATEDATE.le(new Date(searchRequest.getEndDate().getTime())));
        }
        if (StringUtils.isNotBlank(searchRequest.getPetname())){
            loanLargeAmountCondition=loanLargeAmountCondition.and(LOAN_LARGE_AMOUNT_PLUS.NAME.eq(searchRequest.getPetname()));
        }
        if (Objects.nonNull(searchRequest.getC_from())&&searchRequest.getC_from().size()!=0){
            loanLargeAmountCondition=loanLargeAmountCondition.and(LOAN_LARGE_AMOUNT_PLUS.C_FROM.in(searchRequest.getC_from()));
        }
        if (Objects.nonNull(searchRequest.getStatus())){
            loanLargeAmountCondition=loanLargeAmountCondition.and(LOAN_LARGE_AMOUNT_PLUS.STATUS.eq(searchRequest.getStatus()));
        }
        if (Objects.nonNull(searchRequest.getType())){
            loanLargeAmountCondition = loanLargeAmountCondition.and(LOAN_LARGE_AMOUNT_PLUS.TYPE.eq(searchRequest.getType()));
        }
        SelectQuery SPECIFY = dslContext.select(
                LOAN_SPECIFY_PUSH.CREATE_TIME,
                LOAN_SPECIFY_PUSH.CREATEDATE,
                LOAN_SPECIFY_PUSH.TYPE,
                DSL.decode(LOAN_SPECIFY_PUSH.C_FROM,"waitui","外推",LOAN_SPECIFY_PUSH.C_FROM).as("WHERECFROM"),
                LOAN_SPECIFY_PUSH.CHANNEL_ND,
                LOAN_SPECIFY_PUSH.NAME,
                LOAN_SPECIFY_PUSH.AMOUNT,
                LOAN_SPECIFY_PUSH.CITY,
                LOAN_SPECIFY_PUSH.INCOME,
                LOAN_SPECIFY_PUSH.HAS_ESTATE,
                LOAN_SPECIFY_PUSH.HAS_CAR,
                LOAN_SPECIFY_PUSH.LIFE_INSURANCE,
                LOAN_SPECIFY_PUSH.SOCIAL_INSURANCE,
                LOAN_SPECIFY_PUSH.CREDIT,
                DSL.ifnull(null,"未知"),
                DSL.ifnull(null,""),
                LOAN_SPECIFY_PUSH.STATUS,
                LOAN_SPECIFY_PUSH.MOBILE,
                LOAN_SPECIFY_PUSH.HAS_WEILIDAI).from(LOAN_SPECIFY_PUSH).where(specifyCondition).getQuery();

         Table largeAmount = dslContext.select(LOAN_LARGE_AMOUNT_PLUS.field(LOAN_LARGE_AMOUNT_PLUS.CREATE_TIME),
                LOAN_LARGE_AMOUNT_PLUS.field(LOAN_LARGE_AMOUNT_PLUS.CREATEDATE),
                LOAN_LARGE_AMOUNT_PLUS.field(LOAN_LARGE_AMOUNT_PLUS.TYPE).as("TYPE"),
                DSL.ifnull(null,"外推").as("WHERECFROM"),
                LOAN_LARGE_AMOUNT_PLUS.field(LOAN_LARGE_AMOUNT_PLUS.C_FROM),
                LOAN_LARGE_AMOUNT_PLUS.field(LOAN_LARGE_AMOUNT_PLUS.NAME),
                LOAN_LARGE_AMOUNT_PLUS.field(LOAN_LARGE_AMOUNT_PLUS.AMOUNT),
                LOAN_LARGE_AMOUNT_PLUS.field(LOAN_LARGE_AMOUNT_PLUS.CITY),
                LOAN_LARGE_AMOUNT_PLUS.field(LOAN_LARGE_AMOUNT_PLUS.INCOME_FOR_NO_JOB),
                LOAN_LARGE_AMOUNT_PLUS.field(LOAN_LARGE_AMOUNT_PLUS.HAS_ESTATE),
                LOAN_LARGE_AMOUNT_PLUS.field(LOAN_LARGE_AMOUNT_PLUS.HAS_CAR),
                LOAN_LARGE_AMOUNT_PLUS.field(LOAN_LARGE_AMOUNT_PLUS.LIFE_INSURANCE),
                LOAN_LARGE_AMOUNT_PLUS.field(LOAN_LARGE_AMOUNT_PLUS.SOCIAL_INSURANCE),
                LOAN_LARGE_AMOUNT_PLUS.field(LOAN_LARGE_AMOUNT_PLUS.CREDIT),
                LOAN_LARGE_AMOUNT_PLUS.field(LOAN_LARGE_AMOUNT_PLUS.PROFESSION_TYPE),
                LOAN_LARGE_AMOUNT_PLUS.field(LOAN_LARGE_AMOUNT_PLUS.USER_LEVEL), LOAN_LARGE_AMOUNT_PLUS.field(LOAN_LARGE_AMOUNT_PLUS.STATUS), LOAN_LARGE_AMOUNT_PLUS.field(LOAN_LARGE_AMOUNT_PLUS.MOBILE), LOAN_LARGE_AMOUNT_PLUS.field(LOAN_LARGE_AMOUNT_PLUS.HAS_WEILIDAI)
        ).from(LOAN_LARGE_AMOUNT_PLUS).where(loanLargeAmountCondition).unionAll(SPECIFY).asTable("largeAmount");

        Condition condition = DSL.trueCondition();
        if (Objects.nonNull(searchRequest.getWhereCFrom())&&searchRequest.getWhereCFrom().size()!=0){
            if(searchRequest.getWhereCFrom().size()==1&&"站内".equals(searchRequest.getWhereCFrom().get(0))){
                condition = condition.and(largeAmount.field("WHERECFROM").in(getZhanNeiCFrom()));
            }else{
                condition = condition.and(largeAmount.field("WHERECFROM").in(searchRequest.getWhereCFrom()));
            }
        }

        SelectQuery sql = dslContext.select(
                largeAmount.field("TYPE"),
                largeAmount.field("city"),
                largeAmount.field("mobile"),
                largeAmount.field("amount"),
                largeAmount.field("WHERECFROM"),
                largeAmount.field("c_from"),
                largeAmount.field("credit"),
                largeAmount.field("has_car"),
                largeAmount.field("has_estate"),
                largeAmount.field("has_weilidai"),
                largeAmount.field("income_for_no_job"),
                largeAmount.field("life_insurance"),
                largeAmount.field("name"),
                largeAmount.field("profession_type"),
                largeAmount.field("social_insurance"),
                largeAmount.field("user_level"),
                largeAmount.field("createdate"),
                largeAmount.field("status")
        )
                .from(largeAmount)
                .where(condition)
                .orderBy(largeAmount.field("create_time").desc())
                .getQuery();
        return search(sql,pageable,record->{
            LoanLargeAmountPlusRecordSearchResponse response = new LoanLargeAmountPlusRecordSearchResponse();
            response.setApproveamount(record.get(LOAN_LARGE_AMOUNT_PLUS.AMOUNT));

            LoanWholeSaleComment loans = null;
            if (Objects.nonNull(record.get(largeAmount.field("TYPE")))){
                 loans = getWholeSaleInfo(Integer.parseInt(String.valueOf(record.get(largeAmount.field("TYPE")))));
            }
            if(null != loans && StringUtils.isNotBlank(loans.getOwnername())){
                response.setProductName(loans.getOwnername());
            }else{
                response.setProductName("未知");
            }

            String whereCfrom= getStr(record.get(largeAmount.field("WHERECFROM")));
            response.setWhereForm("外推".equals(whereCfrom)?whereCfrom:"站内");

            String c_from = getStr(record.get(largeAmount.field("c_from")));
            response.setC_form(StringUtils.isNotBlank(c_from)?c_from:whereCfrom);

            response.setCity(getStr(record.get(largeAmount.field("city"))));
            response.setCredit(getStr(record.get(largeAmount.field("credit"))));
            response.setHas_car(getStr(record.get(largeAmount.field("has_car"))));
            response.setHas_easten(getStr(record.get(largeAmount.field("has_estate"))));
            response.setHas_weili(getStr(record.get(largeAmount.field("has_weilidai"))));
            response.setIncome(getStr(record.get(largeAmount.field("income_for_no_job"))));
            if (!"0".equals(getStr(record.get(largeAmount.field("life_insurance"))))&&!"1".equals(getStr(record.get(largeAmount.field("life_insurance"))))){
                response.setLife_insurance(getStr(record.get(largeAmount.field("life_insurance"))));
            }else{
                response.setLife_insurance(getStr(record.get(largeAmount.field("life_insurance"))).equals("1")?"有":"否");
            }

            if (StringUtils.isNotBlank(getStr(record.get(largeAmount.field("mobile"))))){
                response.setMobnum(PhoneNumNideUtil.hideNum(getStr(record.get(largeAmount.field("mobile"))),3,4));
            }else{
                response.setMobnum(null);
            }

            response.setProfession_type(getStr(record.get(largeAmount.field("profession_type"))));
            response.setSocial_insurance(getStr(record.get(largeAmount.field("social_insurance"))));
            response.setUser_level(getStr(record.get(largeAmount.field("user_level"))));
            response.setTime(getStr(record.get(largeAmount.field("createdate"))));
            response.setStatus(getIntData(record.get(largeAmount.field("status"))));
            response.setApproveStatus(getStr(record.get(largeAmount.field("status"))));
            response.setPetname(getStr(record.get(largeAmount.field("name"))));
            return response;
        });
    }

    @Override
    public List<String> getCfrom() {
        return dslContext.selectDistinct(LOAN_LARGE_AMOUNT_PLUS.C_FROM)
                .from(LOAN_LARGE_AMOUNT_PLUS)
                .where(LOAN_LARGE_AMOUNT_PLUS.C_FROM.isNotNull())
                .fetch(LOAN_LARGE_AMOUNT_PLUS.C_FROM);
    }


    private String getStr(Object obj){
        if (Objects.nonNull(obj)){
            return String.valueOf(obj);
        }else{
            return null;
        }
    }

    private java.util.Date getDateData(Object obj){
        if (Objects.nonNull(obj)){
            try {
                return DateUtils.formatYyyyMMddToDate(String.valueOf(obj));
            } catch (ParseException e) {
                LogService.error("时间转换异常",e);
            }
        }
        return null;
    }

    private Integer getIntData(Object obj){
        if (Objects.nonNull(obj)){
            return Integer.parseInt(String.valueOf(obj));
        }else{
            return null;
        }
    }
    @Override
    public List<LoanWholeSaleComment> getTypeOwnner(){
        List<LoanWholeSaleComment> loanWholeList = Lists.newArrayList();
        loanWholeList= dslContext.select(LOAN_WHOLESALE_COMMENT.TYPE,LOAN_WHOLESALE_COMMENT.OWNERNAME,
                LOAN_WHOLESALE_COMMENT.WAITUI, LOAN_WHOLESALE_COMMENT.ZHANNEI)
                .from(LOAN_WHOLESALE_COMMENT).where(LOAN_WHOLESALE_COMMENT.TYPE.isNotNull())
                .orderBy(LOAN_WHOLESALE_COMMENT.TYPE.asc()).fetchInto(LoanWholeSaleComment.class);
        return loanWholeList;
    }

    public List<String> getZhanNeiCFrom(){
        List<String> list = Lists.newArrayList();
        list = dslContext.selectDistinct(LOAN_SPECIFY_PUSH.C_FROM)
                .from(LOAN_SPECIFY_PUSH)
                .where(LOAN_SPECIFY_PUSH.C_FROM.isNotNull()
                        .and(LOAN_SPECIFY_PUSH.C_FROM.notEqual("").and(LOAN_SPECIFY_PUSH.C_FROM.notEqual("waitui"))))
                .fetchInto(String.class);
        return list;
    }

    private LoanWholeSaleComment getWholeSaleInfo(Integer type){
        if (loanList==null||loanList.size()<1){
            loanList=getTypeOwnner();
        }
        for (LoanWholeSaleComment var:loanList) {
            if (null != var){
                if (Objects.equals(var.getType(), type)){
                    return var;
                }
            }
        }
        return null;
    }
}
